<template>
  <div style="width: 100%; height: 100%; position: relative">
    <video :id="'video-element-' + id" autoplay :muted="true" style="width: 100%; height: calc(100% - 30px); object-fit: fill"></video>
    <div class="video-control" v-if="showOperate">
      <div class="video-control-item">详情</div>
      <div class="video-control-item">截图</div>
      <div class="video-control-item">麦克风</div>
      <div class="video-control-item">声音</div>
      <div @click="operateCamera()" class="video-control-item">全屏</div>
    </div>

    <div v-if="videoLoadError" class="video-load-error">视频加载失败</div>
  </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import flvUtil from 'flv.js';

const props = defineProps({
  id: {
    type: [Number, String],
    default: ''
  },
  url: propTypes.string.def(''),
  showOperate: {
    type: [Boolean],
    default: true
  },
});
const emit = defineEmits(['openCameraInfo']);

const flvPlayer = ref(null);
const videoLoadError = ref(false);
const loading = ref(true);

const operateCamera = ()=> {
  emit('openCameraInfo', { cameraId: props.id, url: props.url });
}

/**
 * 销毁视频播放器
 */
const destroyFlvPlayer = ()=> {
  if (flvPlayer.value) {
    console.log('销毁视频播器')
    flvPlayer.value.pause();
    flvPlayer.value.unload();
    flvPlayer.value.detachMediaElement();
    flvPlayer.value.destroy();
    flvPlayer.value = null;
  }
}

onMounted(()=> {
  let videoElement = document.getElementById('video-element-'+props.id);
  flvPlayer.value = flvUtil.createPlayer(
    {
      type: "flv", // 媒体类型
      url: props.url, //flv格式媒体URL
      isLive: true, //数据源是否为直播流
      hasAudio: true, //数据源是否包含有音频
      hasVideo: true, //数据源是否包含有视频
      enableStashBuffer: false, //是否启用缓存区
    },
    {
      enableWorker: false, // 是否启用分离的线程进行转换
      enableStashBuffer: false, //关闭IO隐藏缓冲区
      autoCleanupSourceBuffer: true, //自动清除缓存
    }
  );

  flvPlayer.value.attachMediaElement(videoElement);
  flvPlayer.value.load(); //  加载数据流
  // flvPlayer.value.play(); //  播放数据流
  // setTimeout(function () {
  //   flvPlayer.value.play();
  // }, 300);
  flvPlayer.value.on(flvUtil.Events.ERROR, () => {
    videoLoadError.value = true
    loading.value = false
    return false;
  });
  flvPlayer.value.on(flvUtil.Events.LOADING_COMPLETE, ()=> {
    loading.value = false
  });
})
//  在销毁的声明周期中，必须要销毁掉播放器的容器
onBeforeUnmount(()=>{
  destroyFlvPlayer()
})
</script>

<style lang="scss" scoped>
.video-control {
  height: 30px;
  position: absolute;
  bottom: 0;
  right: 10px;
  display: flex;
  align-items: center;
  .video-control-item {
    margin: auto 6px;
  }
}
.video-load-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
